<template>
  <div class="persona-view">
    <!-- 头部工具栏 -->
    <div class="persona-header">
      <div class="header-left">
        <h2>人格管理</h2>
        <div class="persona-stats">
          <span>共 {{ personas.length }} 个人格</span>
          <span>已收藏 {{ favoriteCount }} 个</span>
        </div>
      </div>
      <div class="header-right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索人格..."
          prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        <el-select v-model="selectedCategory" placeholder="分类" clearable>
          <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          创建人格
        </el-button>
      </div>
    </div>

    <!-- 人格列表 -->
    <div class="persona-content">
      <!-- 分类标签 -->
      <div class="category-tabs">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="我的" name="mine" />
          <el-tab-pane label="收藏" name="favorites" />
          <el-tab-pane label="推荐" name="recommended" />
          <el-tab-pane label="热门" name="popular" />
        </el-tabs>
      </div>

      <!-- 人格卡片网格 -->
      <div class="persona-grid" v-loading="loading">
        <div
          v-for="persona in filteredPersonas"
          :key="persona.id"
          class="persona-card"
          @click="selectPersona(persona)"
        >
          <div class="card-header">
            <el-avatar :size="60" :src="persona.avatar" :alt="persona.name">
              {{ persona.name.charAt(0) }}
            </el-avatar>
            <div class="card-actions">
              <el-button
                :type="persona.isFavorite ? 'danger' : 'default'"
                :icon="persona.isFavorite ? 'StarFilled' : 'Star'"
                circle
                size="small"
                @click.stop="toggleFavorite(persona)"
              />
              <el-dropdown @command="handlePersonaAction">
                <el-button
                  type="default"
                  :icon="'MoreFilled'"
                  circle
                  size="small"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'edit', persona }">
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'clone', persona }">
                      克隆
                    </el-dropdown-item>
                    <el-dropdown-item :command="{ action: 'share', persona }">
                      分享
                    </el-dropdown-item>
                    <el-dropdown-item
                      :command="{ action: 'delete', persona }"
                      divided
                      v-if="persona.isOwner"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <div class="card-content">
            <h3 class="persona-name">{{ persona.name }}</h3>
            <p class="persona-description">{{ persona.description }}</p>
            <div class="persona-tags">
              <el-tag
                v-for="tag in persona.tags.slice(0, 3)"
                :key="tag"
                size="small"
                type="info"
              >
                {{ tag }}
              </el-tag>
              <span v-if="persona.tags.length > 3" class="more-tags">
                +{{ persona.tags.length - 3 }}
              </span>
            </div>
          </div>
          <div class="card-footer">
            <div class="persona-stats">
              <span
                ><el-icon><ChatDotRound /></el-icon>
                {{ persona.usageCount }}</span
              >
              <span
                ><el-icon><Star /></el-icon> {{ persona.rating }}</span
              >
            </div>
            <div class="persona-category">
              <el-tag size="small">{{ persona.category }}</el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalCount"
          :page-sizes="[12, 24, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建/编辑人格对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingPersona ? '编辑人格' : '创建人格'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="personaFormRef"
        :model="personaForm"
        :rules="personaRules"
        label-width="80px"
      >
        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload">
            <el-upload
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadAvatar"
            >
              <el-avatar :size="80" :src="personaForm.avatar">
                <el-icon><Plus /></el-icon>
              </el-avatar>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="personaForm.name" placeholder="请输入人格名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="personaForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入人格描述"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="personaForm.category" placeholder="选择分类">
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="personaForm.tags"
            multiple
            filterable
            allow-create
            placeholder="选择或创建标签"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统提示" prop="systemPrompt">
          <el-input
            v-model="personaForm.systemPrompt"
            type="textarea"
            :rows="5"
            placeholder="请输入系统提示词"
          />
        </el-form-item>
        <el-form-item label="配置">
          <el-collapse>
            <el-collapse-item title="高级配置" name="advanced">
              <el-form-item label="温度">
                <el-slider
                  v-model="personaForm.config.temperature"
                  :min="0"
                  :max="2"
                  :step="0.1"
                  show-input
                />
              </el-form-item>
              <el-form-item label="最大长度">
                <el-input-number
                  v-model="personaForm.config.maxTokens"
                  :min="1"
                  :max="4096"
                />
              </el-form-item>
              <el-form-item label="Top P">
                <el-slider
                  v-model="personaForm.config.topP"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  show-input
                />
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="savePersona" :loading="saving">
          {{ editingPersona ? "更新" : "创建" }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 人格详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="人格详情" width="800px">
      <div v-if="selectedPersonaDetail" class="persona-detail">
        <div class="detail-header">
          <el-avatar :size="80" :src="selectedPersonaDetail.avatar">
            {{ selectedPersonaDetail.name.charAt(0) }}
          </el-avatar>
          <div class="detail-info">
            <h2>{{ selectedPersonaDetail.name }}</h2>
            <p>{{ selectedPersonaDetail.description }}</p>
            <div class="detail-tags">
              <el-tag
                v-for="tag in selectedPersonaDetail.tags"
                :key="tag"
                size="small"
                type="info"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="detail-content">
          <el-tabs>
            <el-tab-pane label="基本信息" name="basic">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="分类">
                  {{ selectedPersonaDetail.category }}
                </el-descriptions-item>
                <el-descriptions-item label="创建者">
                  {{ selectedPersonaDetail.creator }}
                </el-descriptions-item>
                <el-descriptions-item label="使用次数">
                  {{ selectedPersonaDetail.usageCount }}
                </el-descriptions-item>
                <el-descriptions-item label="评分">
                  <el-rate v-model="selectedPersonaDetail.rating" disabled />
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ formatDate(selectedPersonaDetail.createdAt) }}
                </el-descriptions-item>
                <el-descriptions-item label="更新时间">
                  {{ formatDate(selectedPersonaDetail.updatedAt) }}
                </el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>
            <el-tab-pane label="系统提示" name="prompt">
              <el-input
                :model-value="selectedPersonaDetail.systemPrompt"
                type="textarea"
                :rows="10"
                readonly
              />
            </el-tab-pane>
            <el-tab-pane label="配置参数" name="config">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="温度">
                  {{ selectedPersonaDetail.config.temperature }}
                </el-descriptions-item>
                <el-descriptions-item label="最大长度">
                  {{ selectedPersonaDetail.config.maxTokens }}
                </el-descriptions-item>
                <el-descriptions-item label="Top P">
                  {{ selectedPersonaDetail.config.topP }}
                </el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="usePersona(selectedPersonaDetail)">
          使用此人格
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  Star,
  StarFilled,
  ChatDotRound,
  MoreFilled,
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { personaApi, fileApi } from "@/api/services";
import { formatDate, debounce } from "@/utils";
import type { Persona, PersonaConfig } from "@/types/chat";

const router = useRouter();

// 响应式数据
const loading = ref(false);
const saving = ref(false);
const personas = ref<Persona[]>([]);
const searchQuery = ref("");
const selectedCategory = ref("");
const activeTab = ref("all");
const currentPage = ref(1);
const pageSize = ref(12);
const totalCount = ref(0);

// 对话框状态
const showCreateDialog = ref(false);
const showDetailDialog = ref(false);
const editingPersona = ref<Persona | null>(null);
const selectedPersonaDetail = ref<Persona | null>(null);

// 表单数据
const personaFormRef = ref();
const personaForm = ref({
  name: "",
  description: "",
  category: "",
  tags: [] as string[],
  systemPrompt: "",
  avatar: "",
  config: {
    temperature: 0.7,
    maxTokens: 2048,
    topP: 0.9,
  } as PersonaConfig,
});

// 表单验证规则
const personaRules = {
  name: [
    { required: true, message: "请输入人格名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入人格描述", trigger: "blur" },
    { min: 10, max: 200, message: "长度在 10 到 200 个字符", trigger: "blur" },
  ],
  category: [{ required: true, message: "请选择分类", trigger: "change" }],
  systemPrompt: [
    { required: true, message: "请输入系统提示词", trigger: "blur" },
    {
      min: 20,
      max: 2000,
      message: "长度在 20 到 2000 个字符",
      trigger: "blur",
    },
  ],
};

// 分类选项
const categories = ref([
  { label: "助手", value: "assistant" },
  { label: "娱乐", value: "entertainment" },
  { label: "教育", value: "education" },
  { label: "创作", value: "creative" },
  { label: "专业", value: "professional" },
  { label: "生活", value: "lifestyle" },
]);

// 可用标签
const availableTags = ref([
  "友善",
  "专业",
  "幽默",
  "严肃",
  "创意",
  "逻辑",
  "情感",
  "技术",
  "艺术",
  "科学",
  "商务",
  "教学",
]);

// 计算属性
const filteredPersonas = computed(() => {
  let result = personas.value;

  // 按标签页过滤
  switch (activeTab.value) {
    case "mine":
      result = result.filter((p) => p.isOwner);
      break;
    case "favorites":
      result = result.filter((p) => p.isFavorite);
      break;
    case "recommended":
      result = result.filter((p) => p.isRecommended);
      break;
    case "popular":
      result = result.filter((p) => p.isPopular);
      break;
  }

  // 按分类过滤
  if (selectedCategory.value) {
    result = result.filter((p) => p.category === selectedCategory.value);
  }

  // 按搜索关键词过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(
      (p) =>
        p.name.toLowerCase().includes(query) ||
        p.description.toLowerCase().includes(query) ||
        p.tags.some((tag) => tag.toLowerCase().includes(query)),
    );
  }

  return result;
});

const favoriteCount = computed(() => {
  return personas.value.filter((p) => p.isFavorite).length;
});

// 方法
const loadPersonas = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      category: selectedCategory.value,
      search: searchQuery.value,
      tab: activeTab.value,
    };
    const response = await personaApi.getPersonas(params);
    personas.value = response.data.list;
    totalCount.value = response.data.total;
  } catch (error) {
    ElMessage.error("加载人格列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = debounce(() => {
  currentPage.value = 1;
  loadPersonas();
}, 300);

const handleTabChange = () => {
  currentPage.value = 1;
  loadPersonas();
};

const handleSizeChange = () => {
  currentPage.value = 1;
  loadPersonas();
};

const handleCurrentChange = () => {
  loadPersonas();
};

const selectPersona = async (persona: Persona) => {
  try {
    const response = await personaApi.getPersonaDetail(persona.id);
    selectedPersonaDetail.value = response.data;
    showDetailDialog.value = true;
  } catch (error) {
    ElMessage.error("获取人格详情失败");
  }
};

const toggleFavorite = async (persona: Persona) => {
  try {
    if (persona.isFavorite) {
      await personaApi.unfavoritePersona(persona.id);
      ElMessage.success("已取消收藏");
    } else {
      await personaApi.favoritePersona(persona.id);
      ElMessage.success("已添加收藏");
    }
    persona.isFavorite = !persona.isFavorite;
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

const handlePersonaAction = async ({
  action,
  persona,
}: {
  action: string;
  persona: Persona;
}) => {
  switch (action) {
    case "edit":
      editPersona(persona);
      break;
    case "clone":
      clonePersona(persona);
      break;
    case "share":
      sharePersona(persona);
      break;
    case "delete":
      deletePersona(persona);
      break;
  }
};

const editPersona = (persona: Persona) => {
  editingPersona.value = persona;
  personaForm.value = {
    name: persona.name,
    description: persona.description,
    category: persona.category,
    tags: [...persona.tags],
    systemPrompt: persona.systemPrompt,
    avatar: persona.avatar,
    config: { ...persona.config },
  };
  showCreateDialog.value = true;
};

const clonePersona = async (persona: Persona) => {
  try {
    const response = await personaApi.clonePersona(persona.id);
    ElMessage.success("人格克隆成功");
    loadPersonas();
  } catch (error) {
    ElMessage.error("克隆失败");
  }
};

const sharePersona = async (persona: Persona) => {
  try {
    const response = await personaApi.sharePersona(persona.id);
    const shareUrl = response.data.shareUrl;
    await navigator.clipboard.writeText(shareUrl);
    ElMessage.success("分享链接已复制到剪贴板");
  } catch (error) {
    ElMessage.error("分享失败");
  }
};

const deletePersona = async (persona: Persona) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除人格 "${persona.name}" 吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning",
      },
    );
    await personaApi.deletePersona(persona.id);
    ElMessage.success("删除成功");
    loadPersonas();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB");
    return false;
  }
  return true;
};

const uploadAvatar = async ({ file }: { file: File }) => {
  try {
    const formData = new FormData();
    formData.append("file", file);
    const response = await uploadApi.uploadImage(formData);
    personaForm.value.avatar = response.data.url;
    ElMessage.success("头像上传成功");
  } catch (error) {
    ElMessage.error("头像上传失败");
  }
};

const savePersona = async () => {
  try {
    await personaFormRef.value.validate();
    saving.value = true;

    if (editingPersona.value) {
      await personaApi.updatePersona(
        editingPersona.value.id,
        personaForm.value,
      );
      ElMessage.success("人格更新成功");
    } else {
      await personaApi.createPersona(personaForm.value);
      ElMessage.success("人格创建成功");
    }

    showCreateDialog.value = false;
    loadPersonas();
  } catch (error) {
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

const resetForm = () => {
  editingPersona.value = null;
  personaForm.value = {
    name: "",
    description: "",
    category: "",
    tags: [],
    systemPrompt: "",
    avatar: "",
    config: {
      temperature: 0.7,
      maxTokens: 2048,
      topP: 0.9,
    },
  };
  personaFormRef.value?.resetFields();
};

const usePersona = (persona: Persona) => {
  // 切换到聊天页面并使用该人格
  router.push({
    name: "Chat",
    query: { personaId: persona.id },
  });
};

// 监听器
watch([selectedCategory], () => {
  currentPage.value = 1;
  loadPersonas();
});

// 生命周期
onMounted(() => {
  loadPersonas();
});
</script>

<style scoped>
.persona-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.persona-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: var(--el-text-color-primary);
}

.persona-stats {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.header-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

.header-right .el-input {
  width: 200px;
}

.header-right .el-select {
  width: 120px;
}

.persona-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.category-tabs {
  margin-bottom: 20px;
}

.persona-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.persona-card {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.persona-card:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.card-content {
  margin-bottom: 12px;
}

.persona-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.persona-description {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.persona-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  align-items: center;
}

.more-tags {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.card-footer .persona-stats {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.card-footer .persona-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding-top: 20px;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar-upload .el-avatar {
  cursor: pointer;
  border: 2px dashed var(--el-border-color);
  transition: border-color 0.3s ease;
}

.avatar-upload .el-avatar:hover {
  border-color: var(--el-color-primary);
}

.persona-detail {
  max-height: 600px;
  overflow: auto;
}

.detail-header {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.detail-info h2 {
  margin: 0 0 8px 0;
  color: var(--el-text-color-primary);
}

.detail-info p {
  margin: 0 0 12px 0;
  color: var(--el-text-color-regular);
  line-height: 1.5;
}

.detail-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.detail-content {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .persona-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-right {
    flex-wrap: wrap;
  }

  .header-right .el-input,
  .header-right .el-select {
    width: 100%;
  }

  .persona-grid {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
  }

  .card-actions {
    align-self: flex-end;
  }

  .detail-header {
    flex-direction: column;
    text-align: center;
  }
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .persona-card:hover {
    box-shadow: 0 4px 12px rgba(255, 255, 255, 0.1);
  }
}
</style>
